import time
import logging
from logging.handlers import TimedRotatingFileHandler

# 配置日志
logger = logging.getLogger('request_timing')
logger.setLevel(logging.INFO)
handler = TimedRotatingFileHandler(
    './mymiddleware/request_timing.log',  # 日志文件名
    when='midnight',  # 每天午夜分割日志文件
    backupCount=7  # 保留最近 7 天的日志
)
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)


# 响应时长中间件
class RequestTimingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    def __call__(self, request):
        start_time = time.time()
        response = self.get_response(request)
        duration = time.time() - start_time
        # 写入日志
        logger.info(f"[{request.method}] {request.path} - {duration:.3f} s")
        print(f"[{request.method}] {request.path} - {duration:.3f} s")
        return response